package workgroup.osaka;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.TextView;

/***************************************
 * アラーム時刻表時エリア
 ****************************************/
public class AlarmDigitalClock extends TextView {
    final private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    private Calendar m_cal;
    private boolean m_tickerStopped = false;
    private Handler m_handler;
    private Runnable m_ticker;
    
    // コンストラクタ
    public AlarmDigitalClock(Context context) {
        super(context);
        initClock(context);
    }
    
    public AlarmDigitalClock(Context context, AttributeSet attrs) {
        super(context, attrs);
        initClock(context);
    }
    
    // 初期化
    private void initClock(Context context) {
        if (m_cal == null) {
            m_cal = Calendar.getInstance();
        }
    }
    
    @Override
    protected void onAttachedToWindow() {
        m_tickerStopped = false;
        super.onAttachedToWindow();
        m_handler = new Handler();
        
        m_ticker = new Runnable() {
            public void run() {
                if (m_tickerStopped == true) return;
                m_cal.setTimeInMillis(System.currentTimeMillis());
                setText(sdf.format(m_cal.getTime()));
                invalidate();
                long now = SystemClock.uptimeMillis();
                long next = now + (1000 - m_cal.getTimeInMillis() % 1000);
                m_handler.postAtTime(m_ticker, next);
            }                
        };
        m_ticker.run();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        m_tickerStopped = true;
    }            
}